package com.small.controller.common.interceptor;

import com.google.common.collect.Maps;
import com.small.common.Const;
import com.small.common.ServerResponse;
import com.small.pojo.User;
import com.small.util.CookieUtil;
import com.small.util.JsonUtil;
import com.small.util.RedisShradedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @create: xie
 * 用户登录、权限过滤器
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //请求中Controller的方法名
        HandlerMethod handlerMethod= (HandlerMethod) o;
        //解析hanlderMethod
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();
//        //解析参数，具体的key\value是什么,打印日志
//        StringBuffer requestParamBuffer=new StringBuffer();
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        Iterator<Map.Entry<String, String[]>> iterator = parameterMap.entrySet().iterator();
//        while(iterator.hasNext()){
//            Map.Entry entry=iterator.next();
//            String mapKey = (String) entry.getKey();
//            String mapValue = StringUtils.EMPTY;
//
//            //request这个参数的map,里面的value返回的是一个string[]
//            Object obj=entry.getValue();
//            if(obj instanceof String[]){
//                String[] strs= (String[]) obj;
//                mapValue= Arrays.toString(strs);
//            }
//            requestParamBuffer.append(mapKey).append("=").append(mapValue);
//        }
        //放行第一次登录
        if(StringUtils.equals(className,"UserManageController") && StringUtils.equals(methodName,"userlogin")){
            return true;
        }
        if(StringUtils.equals(className,"UserController") && StringUtils.equals(methodName,"login")){
            return true;
        }
        if(StringUtils.equals(className,"OrderController") && StringUtils.equals(methodName,"alipayCallback")){
            return true;
        }
        //读取是否有保存token
        User user=null;
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isNotEmpty(loginToken)) {
            String userJsonstr = RedisShradedPoolUtil.get(loginToken);
            //保存已登录用户信息
            user = JsonUtil.string2Obj(userJsonstr, User.class);
        }

        //如果用户是空，或者不是管理员，返回false，不会调用controller的方法,因为无法登陆所以在这里处理返回的错误信息
        if(user==null || (user.getRole().intValue()!= Const.Role.ROLE_ADMIN)){
            response.reset(); //这里要添加reset否则会报异常，通过response返回错误信息
            response.setCharacterEncoding("UTF-8"); //设置编码 否则会乱码
            response.setContentType("application/json;charset=UTF-8");//设置返回值类型，因为全都是json接口
            //输出流
            PrintWriter out=response.getWriter();
            if(user==null){
                //用户为空
                //判断是否是富文本上传操作
                if(StringUtils.equals(className,"ProductManageContoller") && StringUtils.equals(methodName,"richtextImgUpload")){
                   //返回信息特殊处理
                    Map resultmap= Maps.newHashMap();
                    resultmap.put("error",false);
                    resultmap.put("msg","请登录");
                    out.println(JsonUtil.obj2String(resultmap));
                }else{
                    //打印错误信息
                    out.println(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截，用户未登录")));
                }
            }else{
                //不是管理员
                if(StringUtils.equals(className,"ProductManageContoller") && StringUtils.equals(methodName,"richtextImgUpload")){
                    //返回信息特殊处理
                    Map resultmap= Maps.newHashMap();
                    resultmap.put("error",false);
                    resultmap.put("msg","无操作权限");
                    out.println(JsonUtil.obj2String(resultmap));
                }else{
                    out.println(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截，用户无操作权限")));
                }
            }
            out.flush();
            out.close();
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("afterCompletion");
    }
}
